<template>
  <div class="content-box">
    <div class="content">
      <div class="group">
        <div class="header">
          <div class="title">梯控地图</div>
          <div class="handler">
            <div class="showCode">
              <el-switch v-model="showCode" style="--el-switch-on-color: #54bcbd" /><span class="showCodeLabel">显示编码</span>
            </div>
          </div>
        </div>
        <div class="tree">
          <ZTree
            ref="zTreeRef"
            :id="treeId"
            :api="getMapTree"
            :params="{ mapType: 1 }"
            :show-code="showCode"
            :enableDrag="true"
            :checkNodeId="checkNodeId"
            @click-dom="zTreeOnClick"
            @add-hover-dom="addHoverDom"
            @remove-hover-dom="removeHoverDom"
            @on-drop="onDrop"
          />
        </div>
      </div>
      <div class="main">
        <div class="table-box" v-loading="loading">
          <ProTable
            ref="proTable"
            title="梯控点列表"
            rowKey="doorsn"
            :columns="columns"
            :request-api="getTableList"
            :data-callback="dataCallback"
            :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
            :small="true"
            v-if="columns.length"
          >
            <!-- 表格 header 按钮 -->
            <template #tableHeader="scope">
              <el-button type="primary" text :icon="CirclePlus" @click="dialogVisible1 = true">增加梯控点</el-button>
              <el-button type="danger" text :icon="Delete" @click="_batchDel(scope.selectedListIds)">删除</el-button>
            </template>
            <!-- Expand -->
            <template #expand="scope">
              {{ scope.row }}
            </template>
          </ProTable>
        </div>
      </div>
    </div>
    <DoorDialog
      :dialogVisible="dialogVisible1"
      :areaSelList="areaSelList"
      :handleClose="handleClose"
      :mapIds="[mapndx]"
      :submitCallback="_submitDoor"
      v-if="mapndx"
    />
    <el-dialog v-model="dialogVisible" title="上传照片" :before-close="handleClose">
      <el-upload class="upload-demo" drag :show-file-list="false" :http-request="_uploadFile">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖拽文件到这里</div>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="electronMap">
/* eslint-disable */
// @ts-nocheck
import { ref, onMounted, nextTick } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import RoomDrawer from "./components/RoomDrawer.vue";
import DoorDialog from "./components/DoorDialog.vue";
import ZTree from "@/components/ZTree/index.vue";
import { CirclePlus, Delete } from "@element-plus/icons-vue";
import { getMapTree } from "@/api/modules/common";
import {
  getDoorList,
  deleteDoor,
  addDoor,
  getAreaSelList,
  addMapNode,
  delMapNode,
  uploadPhoto,
  editMapNode,
  changeEnabled
} from "@/api/modules/elevatorControl/manage/electronMap";
import { ElMessage, ElMessageBox, UploadRequestOptions } from "element-plus";

const zTreeRef = ref();
const treeId = ref("tree");
const showCode = ref(false);
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const loading = ref(false);
const isDeleting = ref(false);
const areaSelList = ref([]);
const columns: any = ref([]);
const zNodes = ref([]);
const mapndx = ref("");
const curTreeNode = ref("");
const checkNodeId = ref("");

const proTable = ref();

const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  return {
    list: records,
    total: page.total
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading.value = true;
  return getDoorList({ ...newParams, mapIds: [mapndx.value], checkArea: true, enableMode: 2, doorType: 1 });
};

/**
 * 文件上传
 */
const _uploadFile = (uploadFileOpts: UploadRequestOptions) => {
  return new Promise<void>(async resolve => {
    const file = uploadFileOpts!.file;
    const site = file.name.lastIndexOf("\.");

    const fileSuffix = file.name.substring(site + 1, file.name.length);

    const fileTypelist = ["png", "jpg", "jpeg", "gif"];

    if (!fileTypelist.includes(fileSuffix)) {
      ElMessage.error("文件类型不匹配或不支持该种类型文件");
      return false;
    }
    await uploadPhoto({ mapndx: curTreeNode.value.id, photo: file });
    dialogVisible.value = false;
    ElMessage.success("上传成功");
    resolve();
  });
};

const _submitDoor = async ids => {
  try {
    const res = await addDoor({
      list: ids,
      id: mapndx.value
    });
    const { v1, v2 } = res.data;
    ElMessage.success(`增加门禁成功${v1}, 失败${v2}`);
    dialogVisible1.value = false;
  } catch (error) {
    console.log(error);
  }
};

/**
 * 批量删除
 */
const _batchDel = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择梯控点");
    return false;
  }
  ElMessageBox.confirm(`是否删除所选梯控点?`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    try {
      const res = await deleteDoor({ list: selectedListIds, id: mapndx.value });
      const { v1, v2 } = res.data;
      ElMessage.success(`删除成功：${v1},失败：${v2}`);

      proTable.value.clearSelection();
      proTable.value.getTableList();
    } catch (error) {
      console.log(error);
    }
  });
};

/**
 * 切换是否通道
 */
const _changeVisitor = row => {
  console.log(row, "row");
};

/**
 * 切换是否启用
 */
const _changeEnabled = async row => {
  try {
    await changeEnabled({
      id: row.doorsn,
      booleanParam1: !row.enableflag
    });
    ElMessage.success("修改成功");
    proTable.value.getTableList();
  } catch (error) {
    console.log(error);
  }
};

/**
 * 关闭上传照片弹窗
 */
const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
};

const beforeCloseFunc = async (action, instance, done, cb) => {
  if (action === "confirm") {
    instance.confirmButtonLoading = true;
    cb && cb();
  } else {
    done();
  }
};

/**
 * 拖拽节点完成回调
 */
const onDrop = async ({ event, treeId, treeNodes, targetNode, moveType, isCopy, zNode, callback }) => {
  if (zNode.parentId === targetNode?.id || !targetNode) return;
  try {
    const res = await editMapNode({
      mapndx: treeNodes[0].id,
      mapname: treeNodes[0].name,
      maptype: 1,
      parent: targetNode.id,
      nlevel: targetNode.level
    });
    checkNodeId.value = treeNodes[0].id;
    callback && callback();
    ElMessage.success("保存成功");
  } catch (error) {
    console.log(error);
  }
};

/**
 * 获取区域选择列表
 */
const getAreaSelData = async () => {
  try {
    const res = await getAreaSelList();
    areaSelList.value = res.data;
    areaSelList.value.unshift({
      key: "",
      value: "全部"
    });
    areaSelList.value = areaSelList.value.map(item => {
      return {
        ...item,
        label: item.value,
        value: item.key
      };
    });
  } catch (error) {
    console.log(error);
  }
};

/**
 * 点击树节点
 */
function zTreeOnClick({ treeNode }) {
  mapndx.value = "";
  nextTick(() => {
    mapndx.value = treeNode.id;
    proTable.value && proTable.value.getTableList();
  });
}

/**
 * 新增节点
 */
function addNode(treeNode) {
  const zTree = $.fn.zTree.getZTreeObj(treeId.value);
  ElMessageBox.prompt("请输入地图名称", "新增地图", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValidator: val => {
      if (!val) return false;
    },
    inputErrorMessage: "地图名称不能为空",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        try {
          const res = await addMapNode({
            parent: treeNode.id,
            nlevel: treeNode.level + 1,
            maptype: 1,
            mapname: instance.inputValue
          });
          ElMessage.success("新增成功");
          const { mapname, mapndx, maptype, nlevel, parent, scale } = res.data;
          zTree.addNodes(treeNode, { id: mapndx, pId: parent, name: mapname, no: mapndx });
          const node = zTree.getNodeByParam("id", mapndx);
          zTree.selectNode(node);
          $("#" + node.tId + "_a").click();
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
}

/**
 * 删除节点
 */
function removeNode(treeNode) {
  if (!isDeleting.value) {
    useHandleData(delMapNode, { mapndx: treeNode.id }, `删除该地图`, "系统提示").then(() => {
      isDeleting.value = true;
      const zTree = $.fn.zTree.getZTreeObj(treeId.value);
      zTree.removeNode(treeNode, true);
      isDeleting.value = false;
      zTreeRef.value.refresh();
    });
    return false;
  } else {
    return true;
  }
}

/**
 * 编辑节点
 */
function editNode(treeNode, zNode) {
  ElMessageBox.prompt("请输入地图名称", "修改地图", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: zNode.name,
    inputValidator: val => {
      if (!val) return false;
    },
    inputErrorMessage: "地图名称不能为空",
    draggable: true,
    beforeClose: (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        try {
          const res = await editMapNode({
            mapndx: treeNode.id,
            mapname: instance.inputValue,
            maptype: 1,
            parent: treeNode.parentId ?? zNode.parentId,
            nlevel: treeNode.level + 1
          });
          ElMessage.success("修改成功");
          const zTree = $.fn.zTree.getZTreeObj(treeId.value);
          treeNode.name = instance.inputValue;
          zTree.updateNode(treeNode);
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
}

function addHoverDom({ treeId, treeNode, zNode }) {
  const sObj = $("#" + treeNode.tId + "_span");
  if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
  const addStr = "<span class='hoverBtn addBtn' id='addBtn_" + treeNode.tId + "' title='增加' onfocus='this.blur();'></span>";
  const editStr = "<span class='hoverBtn editBtn' id='editBtn_" + treeNode.tId + "' title='修改' onfocus='this.blur();'></span>";
  const removeStr =
    "<span class='hoverBtn removeBtn' id='removeBtn_" + treeNode.tId + "' title='删除' onfocus='this.blur();'></span>";
  const uploadStr =
    "<span class='hoverBtn uploadBtn' id='uploadBtn_" + treeNode.tId + "' title='上传照片' onfocus='this.blur();'></span>";
  const sObjItem = treeNode.parentId ? addStr + editStr + removeStr + uploadStr : addStr + editStr + uploadStr;
  sObj.after(sObjItem);
  const addBtn = $("#addBtn_" + treeNode.tId);
  const editBtn = $("#editBtn_" + treeNode.tId);
  const removeBtn = $("#removeBtn_" + treeNode.tId);
  const uploadBtn = $("#uploadBtn_" + treeNode.tId);
  if (addBtn)
    addBtn.bind("click", function () {
      addNode(treeNode);
      return false;
    });
  if (editBtn)
    editBtn.bind("click", function () {
      editNode(treeNode, zNode);
      return false;
    });
  if (removeBtn)
    removeBtn.bind("click", function () {
      removeNode(treeNode);
      return false;
    });
  if (uploadBtn)
    uploadBtn.bind("click", function () {
      dialogVisible.value = true;
      curTreeNode.value = treeNode;
      return false;
    });
}

function removeHoverDom({ treeNode }) {
  $("#addBtn_" + treeNode.tId)
    .unbind()
    .remove();
  $("#editBtn_" + treeNode.tId)
    .unbind()
    .remove();
  $("#removeBtn_" + treeNode.tId)
    .unbind()
    .remove();
  $("#uploadBtn_" + treeNode.tId)
    .unbind()
    .remove();
}

onMounted(() => {
  Promise.all([getAreaSelData()])
    .then(() => {
      columns.value = [
        { type: "selection", fixed: "left", width: 60 },
        {
          prop: "areaId",
          label: "区域",
          enum: areaSelList.value,
          search: { el: "select", defaultValue: "" },
          isShow: false
        },
        {
          prop: "doorsn",
          label: "梯控点编号",
          minWidth: 200
        },
        {
          prop: "doorname",
          label: "梯控点描述",
          minWidth: 200
        },
        // {
        //   prop: "visitorflag",
        //   label: "是否通道",
        //   minWidth: 120,
        //   render: scope => {
        //     return (
        //       <>
        //         {
        //           <el-switch
        //             model-value={scope.row.visitorflag}
        //             style="--el-switch-on-color: #54bcbd"
        //             onClick={() => {
        //               _changeVisitor(scope.row);
        //             }}
        //           />
        //         }
        //       </>
        //     );
        //   }
        //   // render: scope => {
        //   //   return (
        //   //     <>
        //   //       <el-checkbox disabled v-model={scope.row.visitorflag}></el-checkbox>
        //   //     </>
        //   //   );
        //   // }
        // },
        {
          prop: "enableflag",
          label: "启用",
          render: scope => {
            return (
              <>
                {
                  <el-switch
                    model-value={scope.row.enableflag}
                    style="--el-switch-on-color: #54bcbd"
                    onClick={() => {
                      _changeEnabled(scope.row);
                    }}
                  />
                }
              </>
            );
          },
          minWidth: 120
          // render: scope => {
          //   return (
          //     <>
          //       <el-checkbox disabled v-model={scope.row.enableflag}></el-checkbox>
          //     </>
          //   );
          // }
        }
      ];
    })
    .catch(error => {
      columns.value = [
        { type: "selection", fixed: "left", width: 60 },
        {
          prop: "doorsn",
          label: "梯控点编号",
          minWidth: 200
        },
        {
          prop: "doorname",
          label: "梯控点描述",
          minWidth: 200
        },
        // {
        //   prop: "visitorflag",
        //   label: "是否通道",
        //   minWidth: 120,
        //   render: scope => {
        //     return (
        //       <>
        //         {
        //           <el-switch
        //             model-value={scope.row.visitorflag}
        //             style="--el-switch-on-color: #54bcbd"
        //             onClick={() => {
        //               _changeVisitor(scope.row);
        //             }}
        //           />
        //         }
        //       </>
        //     );
        //   }
        //   // render: scope => {
        //   //   return (
        //   //     <>
        //   //       <el-checkbox disabled v-model={scope.row.visitorflag}></el-checkbox>
        //   //     </>
        //   //   );
        //   // }
        // },
        {
          prop: "enableflag",
          label: "启用",
          render: scope => {
            return (
              <>
                {
                  <el-switch
                    model-value={scope.row.enableflag}
                    style="--el-switch-on-color: #54bcbd"
                    onClick={() => {
                      _changeEnabled(scope.row);
                    }}
                  />
                }
              </>
            );
          },
          minWidth: 120
          // render: scope => {
          //   return (
          //     <>
          //       <el-checkbox disabled v-model={scope.row.enableflag}></el-checkbox>
          //     </>
          //   );
          // }
        }
      ];
      console.log(error);
    });
});
</script>
<style lang="scss">
@import "./index.scss";
</style>
